import { createSlice } from '@reduxjs/toolkit';

// 从 localStorage 获取初始状态
const getInitialState = () => {
    try {
        const savedQuestions = localStorage.getItem('wrongQuestions');
        return {
            wrongQuestions: savedQuestions ? JSON.parse(savedQuestions) : []
        };
    } catch (error) {
        console.error('读取错题本数据失败：', error);
        return { wrongQuestions: [] };
    }
};

const wrongSlice = createSlice({
    name: 'wrong',
    initialState: getInitialState(),
    reducers: {
        addWrongQuestion: (state, action) => {
            console.log('addWrongQuestion reducer 被调用，payload:', action.payload);
            try {
                // 数据验证
                if (!action.payload || !action.payload._id || !action.payload.title) {
                    console.error('错题数据格式不正确：', action.payload);
                    return;
                }

                // 检查是否已存在相同的题目
                const exists = state.wrongQuestions.some(q => q._id === action.payload._id);
                console.log('题目是否已存在：', exists);
                
                if (!exists) {
                    // 确保数据结构完整
                    const wrongQuestion = {
                        _id: action.payload._id,
                        title: action.payload.title,
                        options: Array.isArray(action.payload.options) ? action.payload.options : [],
                        answer: action.payload.answer || '',
                        selectedAnswer: action.payload.selectedAnswer || '',
                        course: action.payload.course || ''
                    };
                    console.log('即将添加到 wrongQuestions 的题目：', wrongQuestion);
                    state.wrongQuestions.push(wrongQuestion);
                    console.log('添加后的 wrongQuestions:', state.wrongQuestions);
                    
                    // 更新 localStorage
                    try {
                        localStorage.setItem('wrongQuestions', JSON.stringify(state.wrongQuestions));
                    } catch (error) {
                        console.error('保存错题本数据失败：', error);
                    }
                }
            } catch (error) {
                console.error('添加错题失败：', error);
            }
        },
        removeWrongQuestion: (state, action) => {
            try {
                state.wrongQuestions = state.wrongQuestions.filter(q => q._id !== action.payload._id);
                // 更新 localStorage
                localStorage.setItem('wrongQuestions', JSON.stringify(state.wrongQuestions));
            } catch (error) {
                console.error('删除错题失败：', error);
            }
        }
    }
});

export const { addWrongQuestion, removeWrongQuestion } = wrongSlice.actions;

// 添加 selector
export const selectWrongQuestions = (state) => {
    try {
        return state.wrong.wrongQuestions || [];
    } catch (error) {
        console.error('获取错题本数据失败：', error);
        return [];
    }
};

export default wrongSlice.reducer; 